package com.example.javaproject.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javaproject.common.R;
import com.example.javaproject.entity.Feedback;
import com.example.javaproject.entity.Position;
import com.example.javaproject.entity.Student;
import com.example.javaproject.entity.Teacher;
import com.example.javaproject.entity.WorkTimeRecord;
import com.example.javaproject.service.FeedbackService;
import com.example.javaproject.service.PositionService;
import com.example.javaproject.service.StudentService;
import com.example.javaproject.service.TeacherService;
import com.example.javaproject.service.WorkTimeRecordService;
import com.example.javaproject.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;

@RestController
@RequestMapping("/api/feedback")
public class FeedbackController {

    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private WorkTimeRecordService workTimeRecordService;

    /**
     * 获取所有岗位列表（用于评价页面显示）- 分页
     */
    @GetMapping("/positions")
    public R getPositionsForFeedback(
            @RequestHeader("Authorization") String authHeader,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "8") int pageSize,
            @RequestParam(required = false) String positionName) {

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }

        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }

        // 获取学生ID
        Student student = studentService.getByUserId(userId);
        if (student == null) {
            return R.error("未找到学生信息");
        }
        Integer studentId = student.getId();

        // 获取学生已工作过的岗位ID集合
        Set<Integer> workedPositionIds = new HashSet<>();
        List<WorkTimeRecord> workRecords = workTimeRecordService.lambdaQuery()
                .eq(WorkTimeRecord::getStudentId, studentId)
                .eq(WorkTimeRecord::getStatus, 1) // 已通过的工时记录
                .eq(WorkTimeRecord::getIsDeleted, false)
                .list();

        for (WorkTimeRecord record : workRecords) {
            workedPositionIds.add(record.getPositionId());
        }

        // 获取所有有反馈的岗位ID
        Set<Integer> feedbackPositionIds = new HashSet<>();
        List<Feedback> feedbacks = feedbackService.list();
        for (Feedback feedback : feedbacks) {
            feedbackPositionIds.add(feedback.getPositionId());
        }

        // 合并所有岗位ID
        Set<Integer> allPositionIds = new HashSet<>();
        allPositionIds.addAll(workedPositionIds);
        allPositionIds.addAll(feedbackPositionIds);

        // 转换为List进行分页
        List<Integer> positionIdList = new ArrayList<>(allPositionIds);

        // 计算分页
        int total = positionIdList.size();
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);

        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            Integer positionId = positionIdList.get(i);
            Position position = positionService.getById(positionId);
            if (position != null) {
                // 如果指定了岗位名称搜索，进行过滤
                if (positionName != null && !positionName.isEmpty()) {
                    if (!position.getName().contains(positionName)) {
                        continue;
                    }
                }

                Map<String, Object> map = new HashMap<>();
                map.put("id", position.getId());
                map.put("name", position.getName());

                // 获取教师名称
                Teacher teacher = teacherService.getById(position.getTeacherId());
                map.put("teacherName", teacher != null ? teacher.getName() : "-");

                // 判断学生是否已工作过该岗位
                map.put("hasWorked", workedPositionIds.contains(positionId));

                result.add(map);
            }
        }

        Map<String, Object> pageData = new HashMap<>();
        pageData.put("records", result);
        pageData.put("total", total);
        pageData.put("current", pageNum);
        pageData.put("size", pageSize);

        return R.ok(pageData);
    }

    /**
     * 获取指定岗位的所有评价
     */
    @GetMapping("/position/{positionId}")
    public R getPositionFeedbacks(
            @RequestHeader("Authorization") String authHeader,
            @PathVariable Integer positionId) {

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }

        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }

        // 获取当前学生ID
        Student currentStudent = studentService.getByUserId(userId);
        if (currentStudent == null) {
            return R.error("未找到学生信息");
        }
        Integer currentStudentId = currentStudent.getId();

        List<Feedback> feedbacks = feedbackService.lambdaQuery()
                .eq(Feedback::getPositionId, positionId)
                .eq(Feedback::getIsDeleted, false)
                .orderByDesc(Feedback::getCreateTime)
                .list();

        List<Map<String, Object>> result = new ArrayList<>();
        for (Feedback feedback : feedbacks) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", feedback.getId());
            map.put("rating", feedback.getRating());
            map.put("comment", feedback.getComment());
            map.put("createTime", feedback.getCreateTime());

            // 获取学生名称
            Student student = studentService.getByUserId(feedback.getStudentId());
            String studentName = student != null ? student.getName() : "匿名";

            // 如果是当前学生的评价，显示真实姓名，否则显示匿名
            if (feedback.getStudentId().equals(currentStudentId)) {
                map.put("studentName", studentName);
                map.put("isOwn", true);
            } else {
                map.put("studentName", "匿名");
                map.put("isOwn", false);
            }

            result.add(map);
        }

        return R.ok(result);
    }

    /**
     * 提交评价
     */
    @PostMapping("/submit")
    public R submitFeedback(
            @RequestHeader("Authorization") String authHeader,
            @RequestBody Map<String, Object> feedbackData) {

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }

        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }

        // 获取学生ID
        Student student = studentService.getByUserId(userId);
        if (student == null) {
            return R.error("未找到学生信息");
        }
        Integer studentId = student.getId();

        // 获取请求参数
        Integer positionId = (Integer) feedbackData.get("positionId");
        String comment = (String) feedbackData.get("comment");
        Integer rating = (Integer) feedbackData.get("rating");

        if (positionId == null || comment == null || rating == null) {
            return R.error("参数不完整");
        }

        if (rating < 1 || rating > 5) {
            return R.error("评分必须在1-5之间");
        }

        // 验证学生是否已工作过该岗位
        boolean hasWorked = workTimeRecordService.lambdaQuery()
                .eq(WorkTimeRecord::getStudentId, studentId)
                .eq(WorkTimeRecord::getPositionId, positionId)
                .eq(WorkTimeRecord::getStatus, 1) // 已通过
                .eq(WorkTimeRecord::getIsDeleted, false)
                .exists();

        if (!hasWorked) {
            return R.error("您还未在该岗位工作过，无法评价");
        }

        // 创建评价记录（允许重复评价）
        Feedback feedback = new Feedback();
        feedback.setPositionId(positionId);
        feedback.setStudentId(studentId);
        feedback.setRating(rating);
        feedback.setComment(comment);
        feedback.setIsDeleted(0);
        feedback.setCreateTime(java.time.LocalDateTime.now());
        feedback.setUpdateTime(java.time.LocalDateTime.now());

        boolean success = feedbackService.save(feedback);
        if (success) {
            return R.ok("评价提交成功");
        } else {
            return R.error("评价提交失败");
        }
    }
}